<style lang="scss" src="./index.scss" scoped></style>
<template>
    <page-box class="form">
        <template v-slot:header>
            <ask-breadcrumb @area-change="handleAreaChange">
                <ask-breadcrumb-item name="MenuSystemManage"></ask-breadcrumb-item>
                <ask-breadcrumb-item name="SystemRoleManage"></ask-breadcrumb-item>
            </ask-breadcrumb>
        </template>
        <main class="form-main">
            <section class="form-drag-box">
                <search-list
                    class="form-main__aside"
                    ref="searchListRef"
                    v-model="searchValue"
                    filterable
                    @filter-method="handleItemSerach"
                    @item-remove="handleItemRemove"
                    @item-add="handleItemAdd"
                    @item-save="handleItemSave"
                    @item-close="handleItemClose"
                    @item-click="handleItemClick"
                    :list="searchList"
                >
                </search-list>
                <div class="form-main__body">
                    <validation-observer ref="observerRef" slim>
                        <el-form
                            class="custom-form"
                            :class="{ role: searchValue !== '' && typeValue === 'role'}"
                            label-position="top"
                            label-width="120px"
                            ref="formRef"
                        >
                            <el-tabs
                                class="theme-gray"
                                v-model="typeValue"
                                @tab-click="handleTabClick"
                            >
                                <el-tab-pane
                                    v-for="item in typeList"
                                    :label="item.label"
                                    :key="item.value"
                                    :name="item.value"
                                >
                                    <div slot="label" class="el-tab__label">
                                        {{ item.label }}
                                    </div>
                                </el-tab-pane>
                            </el-tabs>
                            <div class="role-form__body">
                                <ask-empty-text v-if="searchValue === ''"></ask-empty-text>
                                <template v-else>
                                    <template v-if="typeValue === 'role'">
                                        <el-form-item
                                            class="position-left"
                                            label="状态"
                                        >
                                            <div class="cf__group">
                                                <div class="cf__group-info">
                                                    <el-switch
                                                        v-model="model.disabeld"
                                                        active-color="#13ce66"
                                                        inactive-color="#ff4949"
                                                        active-text="启用"
                                                        inactive-text="禁用"
                                                        :active-value="true"
                                                        :inactive-value="false"
                                                    >
                                                    </el-switch>
                                                </div>
                                                <div class="cf__group-tips"></div>
                                            </div>
                                        </el-form-item>
                                        <page-card label="菜单权限">
                                            <menu-tree
                                                ref="menuTreeRef"
                                                v-model="model.authList"
                                            ></menu-tree>
                                        </page-card>
                                    </template>
                                    <template v-else>
                                        <page-card class="role-people" :label="'成员列表（共计'+peopleNum+'名成员）'">
                                            <people-table
                                                @init="onPeopleTableInit"
                                                :current-pages.sync="currentPage"
                                                :page-sizes.sync="pageSize"
                                                :pageCounts.sync="pageCount"
                                                ref="peopleTableRef"
                                            ></people-table>
                                        </page-card>
                                        <template v-if="pageCount > 0">
                                            <el-pagination
                                                class="pbb__pagination"
                                                @size-change="onPageSizeChange"
                                                @current-change="onCurrentPageChange"
                                                :current-page="currentPage"
                                                :page-sizes="[10, 20, 50, 100]"
                                                :page-size="pageSize"
                                                layout="total, sizes, prev, pager, next, jumper"
                                                :total="pageCount"
                                            >
                                            </el-pagination>
                                        </template>
                                    </template>
                                </template>
                            </div>
                        </el-form>
                    </validation-observer>
                    <footer
                        class="form-main__body-footer"
                        v-if="searchValue !== '' && typeValue === 'role'"
                    >
                        <!-- <el-button plain @click="goBack">取消</el-button> -->
                        <el-button
                            type="primary"
                            @click="sure()"
                            >保存</el-button
                        >
                    </footer>
                </div>
            </section>
        </main>
    </page-box>
</template>

<script lang="ts">
import { Component, Mixins } from "vue-property-decorator";
import FormMixin from "@/mixins/form.mixin.base.ts";
import SearchList from "../components/role-manage/search-list/index.vue";
import MenuTree from "../components/role-manage/menu-tree/index.vue";
import PeopleTable from "../components/role-manage/people-table/index.vue";
import { State } from 'vuex-class';
interface ModelMeta {
    // 权限禁用
    disabeld: boolean;
    // 权限列表
    authList: any[];
}
// const mock = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

@Component({
    name: "SystemRoleManageNotAlive",
    components: {
        SearchList,
        MenuTree,
        PeopleTable
    }
})
export default class SystemRoleManage extends Mixins(FormMixin) {
    @State(state => state.user.userInfo) user: any;
    searchValue = "";
    searchList: any[] = [];

    // 表格数据
    currentPage = 1;
    pageSize = 10;
    pageCount = 0;

    typeValue = "role";
    typeList = [
        {
            label: "角色权限",
            value: "role",
            status: ""
        },
        {
            label: "角色成员",
            value: "people",
            status: ""
        }
    ];

    model: ModelMeta = {
        // 权限禁用
        disabeld: false,
        // 权限列表
        authList: []
    };

    peopleNum = 0;

    mounted() {
        this.$nextTick(() => {
            this.init();
        });
    }

    onPageSizeChange(pageSize: number) {
        this.pageSize = pageSize;
        setTimeout(() => {
            (this.$refs.peopleTableRef as any).initData();
        });
    }

    onCurrentPageChange(page: number) {
        (this.$refs.peopleTableRef as any).initData(page);
    }

    resetModel() {
        this.model = {
            ...this.model,
            authList: [],
            disabeld: false
        };
    }

    handleTabClick() {
        this.$nextTick(() => {
            this.initData();
        });
    }

    handleItemRemove(option: any) {
        this.$confirm(`是否确认删除该角色?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(async() => {
            const item: any = option.item;
            const response = await this.$server["systemManage/roleManage/delete"]({
                data: {
                    id: item.id || ""
                }
            });
            if (this.responseHasError(response)) {
                return;
            }
            this.$message({
                message: '删除成功',
                type: 'success',
                duration: 1500
            });
            if (item.id === this.searchValue) {
                this.searchValue = "";
            }
            this.searchList.splice(option.index, 1);
        }).catch();
    }

    handleItemAdd() {
        this.searchList.push({
            name: "",
            _key: +new Date()
        });
        this.$nextTick(() => {
            const searchListRef: any = this.$refs.searchListRef;
            if (searchListRef) {
                const items: any[] = searchListRef.getChildRef();
                items[this.searchList.length - 1].handleClick("edit");
            }
        });
    }

    handleItemSave(option: any) {
        if (option.editValue !== "") {
            const item = option.item;
            this.submitRole(item.id ? "edit" : "add", option).then((res: any) => {
                if (res) {
                    const data: any = res.data.data || {};
                    this.searchList[option.index].id = data.id;
                    this.searchList[option.index].name = option.editValue;
                    this.searchList[option.index].source = data;
                    const searchListRef: any = this.$refs.searchListRef;
                    searchListRef && searchListRef.close();
                }
            });
        }
    }

    handleItemClose(option: any) {
        if (option.item.name === "") {
            this.searchList.splice(option.index, 1);
        }
    }

    // handleItemClick(option: any) {
    handleItemClick() {
        this.initData();
    }

    // handleItemSerach(search: any, list: any[]) {
    handleItemSerach() {
        return [];
    }

    async init() {
        await this.initSearchListData();
        this.initData();
    }

    initData() {
        this.$nextTick(() => {
            this.peopleNum = 0;
            if (this.typeValue === "role") {
                this.initRoleData();
            } else {
                this.initPeopleData();
            }
        });
    }

    async initRoleData() {
        const menuTreeRef: any = this.$refs.menuTreeRef;
        menuTreeRef && await menuTreeRef.init(this.searchValue);
        this.queryRoleInfo();
    }

    initPeopleData() {
        const peopleTableRef: any = this.$refs.peopleTableRef;
        peopleTableRef && peopleTableRef.init(this.searchValue);
    }

    onPeopleTableInit(opt: any) {
        this.peopleNum = opt.pageCount;
    }

    async initSearchListData() {
        const response = await this.$server["systemManage/roleManage/list"]();
        if (this.responseHasError(response)) {
            return;
        }
        const data = response.data.data || [];
        this.searchList = this.buildTableData(data);
        if (this.searchList.length > 0) {
            this.searchValue = this.searchList[0].id;
        }
    }

    buildTableData(list: any) {
        const res: any = [];
        if (list.length === 0) {
            return res;
        }
        list.forEach((cur: any, index: any) => {
            if (cur.name) {
                res.push({
                    id: cur.id || "",
                    name: cur.name || "",
                    _key: index,
                    source: cur
                });
            }
        });
        return res;
    }

    async submitRole(type: any, option: any) {
        const params: any = {
            // 表格标题
            name: option.editValue || ""
        };
        const axiosInfo: any = {
            url: ""
        };
        if (type === "add") {
            axiosInfo.url = "systemManage/roleManage/add";
        }
        if (type === "edit") {
            params.id = option.item.id;
            axiosInfo.url = "systemManage/roleManage/update";
        }
        // TODO remove
        console.log(params, axiosInfo, type);
        const response = await this.$server[axiosInfo.url]({
            data: params
        });
        if (this.responseHasError(response)) {
            return;
        }
        this.$message({
            message: "操作成功",
            type: "success",
            duration: 1500
        });
        return response;
    }

    async queryRoleInfo() {
        this.resetModel();
        if (this.searchValue === "") return;
        const response = await this.$server["systemManage/roleManage/query"]({
            data: {
                id: this.searchValue
            }
        });
        if (this.responseHasError(response)) {
            return;
        }
        const data = response.data.data || [];
        const model = {
            disabeld: Number(data.roleVo.status) === 1,
            authList: this.buildRoleData(data.menuTreeList || [])
        };
        this.model = {
            ...this.model,
            ...model
        };
    }

    buildRoleData(list: any) {
        let res: any[] = [];
        if (list.length === 0) {
            return res;
        }
        list.forEach((cur: any) => {
            if (cur.children && cur.children.length > 0) {
                const _res: any[] = this.buildRoleData(cur.children);
                res = res.concat(_res);
            } else {
                res.push(cur.id || "");
            }
        });
        return res;
    }

    handleAreaChange() {
        this.init();
    }

    async sure() {
        if (this.searchValue === "") {
            this.$message({
                message: "请先选择角色再操作",
                type: "error",
                duration: 1500
            });
            return;
        }
        const menuTreeRef: any = this.$refs.menuTreeRef;
        const params: any = {
            roleMenuRelationVos: menuTreeRef.getTreeRelation().map((cur: any) => {
                return {
                    menuId: cur.id,
                    roleId: this.searchValue
                };
            }),
            roleVo: {
                id: this.searchValue,
                status: this.model.disabeld ? "1" : "2"
            }
        };
        const response = await this.$server["systemManage/roleManage/updateRole"]({
            data: params
        });
        if (this.responseHasError(response)) {
            return;
        }
        this.$message({
            message: "权限已更新",
            type: "success",
            duration: 1500
        });
    }
}
</script>
